package com.sjzl.util;

import org.apache.commons.fileupload.ProgressListener;

import com.sjzl.entity.ProgressInfo;


public class UploadListener implements ProgressListener {

	private static final long UPDATE_THRESHOLD = 35 * 1024L; // 20KB

	private long megaBytes = -1;

	private ProgressInfo pi = null;

	public UploadListener(ProgressInfo pi) {
		this.pi = pi;
	}

	public void update(long pBytesRead, long pContentLength, int pItems) {
		try {
			Thread.sleep(20);
		} catch (Exception ex) {
			pi.setInProgress(false);
			ex.printStackTrace();
		}

		long mBytes = pBytesRead / UPDATE_THRESHOLD;
		if (megaBytes == mBytes && megaBytes > 0) {
			return;
		}

		megaBytes = mBytes;
		pi.setBytesRead(pBytesRead);
		pi.setFileIndex(pItems);
		pi.setTotalSize(pContentLength);

		if (pBytesRead + UPDATE_THRESHOLD >= pContentLength) {
			pi.setCompleted(true);
			Util.info("UploadListener", pBytesRead + ";" + pItems + ";"
					+ pContentLength);
			Util.info("UploadListener ->> update ", "Completed");
		}
	}
}
